package alloy.gui;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import alloy.api.LiftedUnsatCore;
import alloy.ast.Formula;
import alloy.ast.Location;
import alloy.ast.Node;

class ASTViewer extends JFrame {

    public ASTViewer(LiftedUnsatCore core_, Formula formula_, LocatableTextArea textArea_) {
	super("AST Viewer");

	// build the tree
	buildTreeDisplay(core_, formula_, textArea_);
    }

    public void buildTreeDisplay(LiftedUnsatCore core_, Formula formula_, final LocatableTextArea textArea_) {

	DefaultMutableTreeNode ast = VerySimpleSwingASTVisitor.buildSwingAST(core_, formula_);

	JTree treeDisplay = new JTree(ast);
	treeDisplay.setCellRenderer(new SwingASTRenderer());
	
	treeDisplay.addTreeSelectionListener(new TreeSelectionListener () {
		public void valueChanged(TreeSelectionEvent e_) {
		    TreePath selPath = e_.getNewLeadSelectionPath();
		    if (selPath == null ||
			!(selPath.getLastPathComponent() instanceof DefaultMutableTreeNode) ||
			((DefaultMutableTreeNode)selPath.getLastPathComponent()).getUserObject() == null ||
			!(((DefaultMutableTreeNode)selPath.getLastPathComponent()).getUserObject()
			  instanceof NodeInfo))
			{
			    return;
			}
		    // determine the AST node represented by the Swing node that was clicked
		    NodeInfo swingNodeInfo =
			(NodeInfo)((DefaultMutableTreeNode)selPath.getLastPathComponent()).getUserObject();
		    Node node = swingNodeInfo.getNode();
		    if (node!=null) {
			// highlight the corresponding source.
			Location loc = node.getLocation();
			textArea_.showLoc(loc);
			
			//if (loc == Location.UNKNOWN && node instanceof TreeNode) {
			//System.out.println(((TreeNode)node).getCreationInfo());
			    //}
			
			// show template info
			//			    controller.printNodeInfo(node);
		    }
		    }
	    });
	
	setSize(400, 600);
	getContentPane().add(new JScrollPane(treeDisplay));
	setVisible(true);

    }

}
